#include "led_control.h"
#include "driver/rmt.h"
#include "esp_log.h"
#include "freertos/task.h"

static const char *TAG = "LED_CONTROL";
#define RMT_TX_CHANNEL RMT_CHANNEL_0

// WS2812B时序参数（单位：ns）
#define WS2812_T0H_NS  350
#define WS2812_T0L_NS  900
#define WS2812_T1H_NS  900
#define WS2812_T1L_NS  350
#define WS2812_RESET_US 280

// 将ns时间转换为RMT ticks
static uint32_t ns_to_rmt_ticks(uint32_t ns, uint32_t clock_hz) {
    return (ns * (clock_hz / 1000)) / 1000000;
}

void setup_rmt() {
    rmt_config_t config = RMT_DEFAULT_CONFIG_TX(LED_GPIO, RMT_TX_CHANNEL);
    config.clk_div = 2; // 80MHz / 2 = 40MHz，每个tick=25ns
    
    ESP_ERROR_CHECK(rmt_config(&config));
    ESP_ERROR_CHECK(rmt_driver_install(config.channel, 0, 0));
}

void set_led_color(uint32_t gerb) {
    uint32_t rmt_ticks_t0h = ns_to_rmt_ticks(WS2812_T0H_NS, 40000000);
    uint32_t rmt_ticks_t0l = ns_to_rmt_ticks(WS2812_T0L_NS, 40000000);
    uint32_t rmt_ticks_t1h = ns_to_rmt_ticks(WS2812_T1H_NS, 40000000);
    uint32_t rmt_ticks_t1l = ns_to_rmt_ticks(WS2812_T1L_NS, 40000000);
    
    rmt_item32_t items[24];
    
    for (int i = 0; i < 24; i++) {
        if (gerb & (1 << (23 - i))) {
            // 发送1码
            items[i].level0 = 1;
            items[i].duration0 = rmt_ticks_t1h;
            items[i].level1 = 0;
            items[i].duration1 = rmt_ticks_t1l;
        } else {
            // 发送0码
            items[i].level0 = 1;
            items[i].duration0 = rmt_ticks_t0h;
            items[i].level1 = 0;
            items[i].duration1 = rmt_ticks_t0l;
        }
    }
    
    ESP_ERROR_CHECK(rmt_write_items(RMT_TX_CHANNEL, items, 24, true));
    
    // 发送复位信号
    vTaskDelay(pdMS_TO_TICKS(WS2812_RESET_US / 1000));
}

void led_control_init() {
    setup_rmt();
    ESP_LOGI(TAG, "LED控制初始化完成");
}

void wifi_connected_led_indicator() {
    // WiFi连接成功后，LED显示绿色5秒
    set_led_color(COLOR_GREEN);
    vTaskDelay(pdMS_TO_TICKS(5000)); // 持续5秒
    set_led_color(COLOR_OFF); // 关闭LED
}